#!/usr/bin/perl

package DB::Base;

use strict;
use warnings;

use Consts;
use Carp qw(croak);
use Utils qw(dd);
use Log;

our $VERSION = '0.1';

sub new
{
    my $class = shift;
    my $self = {
        _config => shift
    };
    bless $self, $class;
    return $self;
}

sub getConfig
{
    my $self = shift;
    return $self->{_config};
}

sub connect
{
    my $self = shift;
    my %args = @_;
    my $host = $args{host};
}

sub getCommand
{
    croak "getCommand method must be implemented by subclass";
}

sub connectDB
{
    croak "connectDB method must be implemented by subclass";
}

sub getVersion
{
    croak "getVersion method must be implemented by subclass";
}

sub getCount
{
    croak "getCount method must be implemented by subclass";
}

sub getNumericColumns
{
    croak "getNumericColumns method must be implemented by subclass";
}

sub getColumnSum
{
    croak "getColumnSum method must be implemented by subclass";
}

sub getStringColumns
{
    croak "getStringColumns method must be implemented by subclass";
}

sub getAmplingConditions
{
    croak "getAmplingConditions method must be implemented by subclass";
}

sub getRandomRow
{
    croak "getRandomRow method must be implemented by subclass";
}

sub getSamplingRows
{
    croak "getSamplingRows method must be implemented by subclass";
}

sub getDBH
{
    my $self = shift;
    return $self->{dbh};
}

sub getSql
{
    my ($self, $sql_name) = @_;
    my $sql_path = $Consts::CONFIG_PATH . $Consts::DS . "sql" . $Consts::DS . $sql_name . ".sql";
    unless (-f $sql_path) {
        croak "No sql template found: ${sql_path}";
    }
    open (my $fh, '<', $sql_path) or croak "Failed to open file: $!";
    my $sql = do { local $/; <$fh> };
    close($fh);
    return $sql;
}

sub getRow
{
    my ($self, $sql) = @_;
    my $sth = $self->{dbh}->prepare($sql);
    $sth->execute();
    my $row = $sth->fetchrow_hashref();
    return $row;
}

sub getRows
{
    my ($self, $sql) = @_;
    my $sth = $self->{dbh}->prepare($sql);
    $sth->execute();
    my @rows;
    while (my $row = $sth->fetchrow_hashref()) {
        push @rows, $row;
    }
    return @rows;
}

1;